/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.unisc.pdaapp.server.webservice;

import br.unisc.pdaapp.meta.FileUtil;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import br.unisc.pdaapp.meta.ws.IMoodleMobileWS;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 *
 * @author guilherme
 */
public class MoodleMobileWS implements IMoodleMobileWS
{

    private Connection connection;
    private BASE64Encoder base64Encoder;
    private static final String MOODLE_TABLE_PREFIX = "mdl_";

    public MoodleMobileWS()
    {
        base64Encoder = new BASE64Encoder();
    }

    private Connection getConnection() throws SQLException, IOException
    {
        if (connection != null)
        {
            return connection;
        }

        InputStream inputStream = getClass().getResourceAsStream("database.properties");

        Properties props = new Properties();
        props.load(inputStream);

        String host = props.getProperty("HOST");
        String db = props.getProperty("DBNAME");
        String user = props.getProperty("USER");
        String password = props.getProperty("PWD");

        String url = "jdbc:mysql://" + host + "/" + db;
        String driver = "com.mysql.jdbc.Driver";

        try
        {
            System.out.println("Conectando ao banco");
            Class.forName(driver);
            return DriverManager.getConnection(url, user, password);
        }
        catch (ClassNotFoundException e)
        {
            throw new SQLException(e.getMessage());
        }
    }

    public int doLogin(String userName, String passwd)
    {
        System.out.println(">>> doLogin method");

        try
        {
            String query = "SELECT u.username, u.password, r.shortname ";
            query += " FROM " + MOODLE_TABLE_PREFIX + "user u, ";
            query += " " + MOODLE_TABLE_PREFIX + "role_assignments ra, ";
            query += " " + MOODLE_TABLE_PREFIX + "context con, ";
            query += " " + MOODLE_TABLE_PREFIX + "course c, ";
            query += " " + MOODLE_TABLE_PREFIX + "role r ";
            query += " WHERE ";
            query += " u.id = ra.userid AND ";
            query += " ra.contextid = con.id AND ";
            query += " con.contextlevel = 50 AND ";
            query += " con.instanceid = c.id AND ";
            query += " ra.roleid = r.id AND ";
            query += " u.username = '" + userName + "' AND ";
            query += " u.password = '" + passwd + "'";

            PreparedStatement statement = getConnection().prepareStatement(query);
            ResultSet rs = statement.executeQuery();

            if (rs.next())
            {
                String shortName = rs.getString("shortname");

                System.out.println("Succes login for: " + shortName + ", " + userName);

                if (shortName.contains("student"))
                {
                    return SUCCES_LOGIN_STUDENT;
                }
                else
                {
                    return SUCCES_LOGIN_TEACHER;
                }
            }
            else
            {
                System.out.println("Failed login");
                return FAILED_LOGIN;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return FAILED_LOGIN;
    }

    public byte[] getCourses(String userName)
    {
        System.out.println(">>> getCourses method");

        ResultSet rs = null;
        PreparedStatement statement = null;

        try
        {
            String query = "SELECT";
            query += " u.username,";
            query += " c.id,";
            query += " c.fullname,";
            query += " r.shortname";
            query += " FROM";
            query += " " + MOODLE_TABLE_PREFIX + "user u,";
            query += " " + MOODLE_TABLE_PREFIX + "role_assignments ra,";
            query += " " + MOODLE_TABLE_PREFIX + "context con,";
            query += " " + MOODLE_TABLE_PREFIX + "course c,";
            query += " " + MOODLE_TABLE_PREFIX + "role r";
            query += " WHERE";
            query += " u.id = ra.userid AND";
            query += " ra.contextid = con.id AND";
            query += " con.contextlevel = 50 AND";
            query += " con.instanceid = c.id AND";
            query += " ra.roleid = r.id AND";
            query += " u.username = '" + userName + "'";
            query += " GROUP BY c.id";

            System.out.println("Trying to execute query:");
            System.out.println("query: " + query);

            statement = getConnection().prepareStatement(query);
            rs = statement.executeQuery();

            System.out.println("Query executed!");
            System.out.println("Retrievieng courses data.");

            StringBuffer buffer = new StringBuffer();

            buffer.append("<?xml version=\"1.0\"?>");
            buffer.append("<root>");

            while (rs.next())
            {
                String courseID = rs.getString("id");
                String courseName = rs.getString("fullname");

                buffer.append("<course>");
                buffer.append("<cid>" + courseID + "</cid>");
                buffer.append("<cname>" + courseName + "</cname>");
                buffer.append("</course>");
            }

            buffer.append("</root>");

            System.out.println("xml: " + buffer.toString());

            byte[] bytes = buffer.toString().getBytes();

            return base64Encoder.encode(bytes).getBytes();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                rs.close();
                statement.close();
            }
            catch (SQLException ex)
            {
                Logger.getLogger(MoodleMobileWS.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return null;
    }

    public byte[] getClasses(int courseID)
    {
        System.out.println(">>> getClasses method");

        ResultSet rs = null;
        PreparedStatement statement = null;

        try
        {
            String query = "SELECT ";
            query += " sec.id, ";
            query += " sec.section, ";
            query += " sec.summary, ";
            query += " sec.visible ";
            query += " FROM " + MOODLE_TABLE_PREFIX + "course_sections sec ";
            query += " WHERE course = " + courseID;
            query += " ORDER BY sec.section";

            System.out.println("Trying to execute query:");
            System.out.println("query: " + query);

            statement = getConnection().prepareStatement(query);
            rs = statement.executeQuery();

            System.out.println("Query executed!");
            System.out.println("Retrievieng classes data.");

            StringBuffer buffer = new StringBuffer();

            buffer.append("<?xml version=\"1.0\"?>");
            buffer.append("<root>");

            while (rs.next())
            {
                String classID = rs.getString("id");
                String section = rs.getString("section");
                String visible = rs.getString("visible");
                String summary = rs.getString("summary");

                summary = summary != null ? summary.replaceAll("<br />", "") : "";

                buffer.append("<csection>");
                buffer.append("<sid>" + classID + "</sid>");
                buffer.append("<sec>" + section + "</sec>");
                buffer.append("<vis>" + visible + "</vis>");
                buffer.append("<sum>" + summary + "</sum>");
                buffer.append("</csection>");
            }

            buffer.append("</root>");

            System.out.println("xml: " + buffer.toString());

            byte[] bytes = buffer.toString().getBytes();

            return base64Encoder.encode(bytes).getBytes();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                rs.close();
                statement.close();
            }
            catch (SQLException ex)
            {
                Logger.getLogger(MoodleMobileWS.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return null;
    }

    public byte[] getMaterial(int courseID, int courseSectionID)
    {
        System.out.println(">>> getMaterial method");

        ResultSet rs = null;
        PreparedStatement statement = null;

        try
        {
            String query = "select ";
            query += " cm.instance, ";
            query += " cm.id as cm_id, m.id as m_id, cm.visible, ";
            query += " r.name as itm_name, r.reference as itm_desc ";
            query += "from " + MOODLE_TABLE_PREFIX + "resource r ";
            query += " inner join " + MOODLE_TABLE_PREFIX + "course c on c.id = r.course ";
            query += " inner join " + MOODLE_TABLE_PREFIX + "course_modules cm on cm.course = c.id and cm.instance = r.id ";
            query += " inner join " + MOODLE_TABLE_PREFIX + "modules m on cm.module = m.id ";
            query += "WHERE  ";
            query += " c.id = " + courseID;
            query += " and cm.section = " + courseSectionID;
            query += " and m.id = 13 "; // para resources
            query += "UNION ALL ";
            query += "select  ";
            query += " cm.instance, ";
            query += " cm.id as cm_id, m.id as m_id, cm.visible, ";
            query += " l.name as itm_name, l.content as itm_desc ";
            query += "from " + MOODLE_TABLE_PREFIX + "label l ";
            query += " inner join " + MOODLE_TABLE_PREFIX + "course_modules cm on cm.instance = l.id and cm.course = l.course ";
            query += " inner join " + MOODLE_TABLE_PREFIX + "course c on c.id = l.course and cm.course = c.id ";
            query += " inner join " + MOODLE_TABLE_PREFIX + "modules m on cm.module = m.id ";
            query += "WHERE  ";
            query += " c.id = " + courseID;
            query += " and cm.section = " + courseSectionID;
            query += " and m.id = 9 "; //para labels

            System.out.println("Trying to execute query:");
            System.out.println("query: " + query);

            statement = getConnection().prepareStatement(query);
            rs = statement.executeQuery();

            System.out.println("Query executed!");
            System.out.println("Retrievieng material data.");

            StringBuffer buffer = new StringBuffer();

            buffer.append("<?xml version=\"1.0\"?>");
            buffer.append("<root>");

            while (rs.next())
            {
                String instance = rs.getString("instance");
                String cmID = rs.getString("cm_id");
                String mID = rs.getString("m_id");
                String itmName = rs.getString("itm_name");
                String itmDesc = rs.getString("itm_desc");
                String visible = rs.getString("visible");

                itmName = itmName != null ? itmName.replaceAll("<br />", "") : "";

                buffer.append("<material>");
                buffer.append("<inst>" + instance + "</inst>");
                buffer.append("<cmid>" + cmID + "</cmid>");
                buffer.append("<mid>" + mID + "</mid>");
                buffer.append("<itname>" + itmName + "</itname>");
                buffer.append("<itdesc>" + itmDesc + "</itdesc>");
                buffer.append("<vis>" + visible + "</vis>");
                buffer.append("</material>");
            }

            buffer.append("</root>");

            System.out.println("xml: " + buffer.toString());

            byte[] bytes = buffer.toString().getBytes();

            return base64Encoder.encode(bytes).getBytes();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                rs.close();
                statement.close();
            }
            catch (SQLException ex)
            {
                Logger.getLogger(MoodleMobileWS.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return null;
    }

    public int updateClassVisibility(int courseID, int sectionID, boolean visible)
    {
        PreparedStatement statement = null;

        try
        {
            String update = "update " + MOODLE_TABLE_PREFIX + "course_sections cs ";
            update += " set cs.visible = " + (visible ? 1 : 0);
            update += " where ";
            update += " cs.course = " + courseID;
            update += " and cs.id = " + sectionID;

            statement = getConnection().prepareStatement(update);

            //faz o update
            statement.execute();

            System.out.println("Well done! Section visibility updated successfully!");

            return 1;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                statement.close();
            }
            catch (SQLException ex)
            {
                Logger.getLogger(MoodleMobileWS.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return -1;
    }

    public int updateMaterialVisibility(int instance, int courseID, int courseSectionID, int courseModuleID, boolean visible)
    {
        PreparedStatement statement = null;

        try
        {
            String update = "update " + MOODLE_TABLE_PREFIX + "course_modules cm ";
            update += " set cm.visible = " + (visible ? 1 : 0);
            update += " WHERE ";
            update += " cm.course = " + courseID;
            update += " and cm.instance = " + instance;
            update += " and cm.section = " + courseSectionID;
            update += " and cm.module = " + courseModuleID;

            statement = getConnection().prepareStatement(update);

            //faz o update
            statement.execute();

            System.out.println("Well done! Course Module visibility updated successfully!");

            return 1;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                statement.close();
            }
            catch (SQLException ex)
            {
                Logger.getLogger(MoodleMobileWS.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return -1;
    }

    public int deleteMessage(int messageID)
    {
        System.out.println(">>> deleteMessage method");

        PreparedStatement statement = null;

        try
        {
            String insert = "insert into " + MOODLE_TABLE_PREFIX + "message_read";

            String columns = "useridfrom, ";
            String values = "select useridfrom, ";

            columns += "useridto, ";
            values += "useridto, ";

            columns += "message, ";
            values += "message, ";

            columns += "format, ";
            values += "1, ";

            columns += "timecreated, ";
            values += "timecreated, ";

            columns += "timeread, ";
            values += "0, ";

            columns += "messagetype, ";
            values += "'direct', ";

            columns += "mailed";
            values += "0 ";

            values += "from " + MOODLE_TABLE_PREFIX + "message ";
            values += "where id = " + messageID + ";";

            statement = getConnection().prepareStatement(insert + " (" + columns + ") " + values);
            statement.execute();

            //Delete the message.
            String delete = "delete from " + MOODLE_TABLE_PREFIX + "message where id = " + messageID;
            statement.execute(delete);

            System.out.println("Well done! Message deleted successfully!");

            return 1;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                statement.close();
            }
            catch (SQLException ex)
            {
                Logger.getLogger(MoodleMobileWS.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return -1;
    }

    public byte[] getMessages(String userName)
    {
        System.out.println(">>> getMessages method");

        ResultSet rs = null;
        PreparedStatement statement = null;

        try
        {
            String query = "select ";
            query += "m.id, u2.username as userfrom, m.message ";
            query += "from " + MOODLE_TABLE_PREFIX + "message m ";
            query += "inner join " + MOODLE_TABLE_PREFIX + "user u1 on u1.id = m.useridto ";
            query += "inner join " + MOODLE_TABLE_PREFIX + "user u2 on u2.id = m.useridfrom ";
            query += "where m.useridto = (select id from " + MOODLE_TABLE_PREFIX + "user where username = '" + userName + "')";

            System.out.println("Trying to execute query:");
            System.out.println("query: " + query);

            statement = getConnection().prepareStatement(query);
            rs = statement.executeQuery();

            System.out.println("Query executed!");
            System.out.println("Retrievieng messages data.");

            StringBuffer buffer = new StringBuffer();

            buffer.append("<?xml version=\"1.0\"?>");
            buffer.append("<root>");

            while (rs.next())
            {
                String messageID = rs.getString("id");
                String userfrom = rs.getString("userfrom");
                String message = rs.getString("message");

                message = message != null ? message.replaceAll("<br />", "\n") : "";

                buffer.append("<msg>");
                buffer.append("<mid>" + messageID + "</mid>");
                buffer.append("<from>" + userfrom + "</from>");
                buffer.append("<msg_val>" + message + "</msg_val>");
                buffer.append("</msg>");
            }

            buffer.append("</root>");

            System.out.println("xml: " + buffer.toString());

            byte[] bytes = buffer.toString().getBytes();

            return base64Encoder.encode(bytes).getBytes();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                rs.close();
                statement.close();
            }
            catch (SQLException ex)
            {
                Logger.getLogger(MoodleMobileWS.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return null;
    }

    public int sendMessage(String fromUserName, String destUsers, String message)
    {
        System.out.println(">>> getMessages method");

        if (destUsers == null || destUsers.split(";").length == 0)
        {
            //Deve haver ao menos um usuário de destino.
            return -1;
        }

        ResultSet rsUser = null;
        ResultSet rs = null;
        PreparedStatement statement = null;

        try
        {
            String query = "select m.id ";
            query += " from " + MOODLE_TABLE_PREFIX + "user m ";
            query += " where m.username = '" + fromUserName + "'";

            statement = getConnection().prepareStatement(query);
            rs = statement.executeQuery();

            System.out.println("Trying to retrieve user.");
            System.out.println("query: " + query);

            if (rs.next())
            {
                String userFromID = rs.getString("id");

                String insert = "insert into " + MOODLE_TABLE_PREFIX + "message";
                String fields = "useridfrom";
                String values = userFromID;

                fields += ", useridto";
                values += ", ?";

                fields += ", message";
                values += ", '" + message + "'";

                fields += ", format";
                values += ", 1";

                fields += ", timecreated";
                values += ", " + new Date().getTime();

                fields += ", messagetype";
                values += ", 'direct'";

                insert = insert + "(" + fields + ") values (" + values + ")";

                String[] dests = destUsers.split(";");

                for (String destUser : dests)
                {
                    System.out.println("insert: " + insert);

                    statement = getConnection().prepareStatement("select id from " + MOODLE_TABLE_PREFIX + "user where username = '" + destUser + "'");
                    rsUser = statement.executeQuery();

                    int destUserID = -1;

                    if (rsUser.next())
                    {
                        destUserID = rsUser.getInt("id");
                    }
                    else
                    {
                        //Erro
                        new Exception("Usuario destino inválido: " + destUser).printStackTrace();
                        return -1;
                    }

                    statement = getConnection().prepareStatement(insert);
                    statement.setInt(1, destUserID);

                    //realiza o insert.
                    statement.execute();
                }
            }
            else
            {
                //Erro: usuário from inválido.
                return -1;
            }

            System.out.println("Well done! Message sent successfully!");

            return 1;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                rsUser.close();
                rs.close();
                statement.close();
            }
            catch (SQLException ex)
            {
                Logger.getLogger(MoodleMobileWS.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return -1;
    }

    public byte[] getUsersByCourse(int courseID)
    {
        /**
         * CONTEXT_COURSE = 50
         * Está variavel é definida no arquivo moodle/lib/accesslib.php.
         * Talvez em versões futuras está pode ser alterada.
         * Caso ocorra alguma inconsistência no programa está pode ser uma das razões.
         */
        System.out.println(">>> getUsers method");

        ResultSet rs = null;
        PreparedStatement statement = null;

        try
        {
            String query = "select u.username, r.shortname ";
            query += "from " + MOODLE_TABLE_PREFIX + "role_assignments ra ";
            query += "inner join " + MOODLE_TABLE_PREFIX + "user u on u.id = ra.userid ";
            query += "inner join " + MOODLE_TABLE_PREFIX + "role r on r.id = ra.roleid ";
            query += "where ra.contextid = (";
            query += " select id ";
            query += " from " + MOODLE_TABLE_PREFIX + "context ";
            query += " where instanceid = " + String.valueOf(courseID);
            query += "   and contextlevel = 50) ";
            query += "group by ra.userid ";

            System.out.println("Trying to execute query:");
            System.out.println("query: " + query);

            statement = getConnection().prepareStatement(query);
            rs = statement.executeQuery();

            System.out.println("Query executed!");
            System.out.println("Retrievieng users data.");

            StringBuffer buffer = new StringBuffer();

            buffer.append("<?xml version=\"1.0\"?>");
            buffer.append("<root>");

            while (rs.next())
            {
                String userName = rs.getString("username");
                String shortName = rs.getString("shortname");

                buffer.append("<user>");
                buffer.append("<name>" + userName + "</name>");
                buffer.append("<isStudent>" + (shortName.equalsIgnoreCase("student") ? 1 : 0) + "</isStudent>");
                buffer.append("</user>");
            }

            buffer.append("</root>");

            System.out.println("xml: " + buffer.toString());

            byte[] bytes = buffer.toString().getBytes();

            return base64Encoder.encode(bytes).getBytes();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                rs.close();
                statement.close();
            }
            catch (SQLException ex)
            {
                Logger.getLogger(MoodleMobileWS.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return null;
    }

    public byte[] downloadMaterial(int courseID, String fileName)
    {
        try
        {
            byte[] fileBytes = null;
            String moodleDataDirPath = "/media/disk/projetos/www/moodledata";

            File file = new File(moodleDataDirPath + File.separatorChar + courseID, fileName);
            fileBytes = FileUtil.getBytesFromFile(file);

            System.out.println("Well done! File has been sent successful!");

            return fileBytes;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return null;
    }

    public int uploadMaterial(int courseID, int courseSectionID, String file, String fileName)
    {
        PreparedStatement courseModuleStatement = null;
        PreparedStatement selectStatement = null;
        ResultSet rs = null;

        try
        {
            String query = "select max(id) + 1 as newid from " + MOODLE_TABLE_PREFIX + "resource";
            selectStatement = getConnection().prepareStatement(query);
            rs = selectStatement.executeQuery();

            int newID = 1;
            if (rs.next())
            {
                newID = Integer.parseInt(rs.getString("newid"));
            }

            String insert = "insert into " + MOODLE_TABLE_PREFIX + "resource";

            String fields = "id";
            String values = "" + newID;

            fields += ", course";
            values += ", " + courseID;

            fields += ", name";
            values += ", '" + fileName + "'";

            fields += ", type";
            values += ", 'file'";

            fields += ", reference";
            values += ", '" + fileName + "'";

            fields += ", summary";
            values += ", ''";

            fields += ", alltext";
            values += ", ''";

            fields += ", popup";
            values += ", ''";

            fields += ", options";
            values += ", ''";

            fields += ", timemodified";
            values += ", " + new Date().getTime();

            insert = insert + "(" + fields + ") values (" + values + ")";

            System.out.println("insert: " + insert);

            PreparedStatement resourceStatement = getConnection().prepareStatement(insert);
            //realiza o insert.
            resourceStatement.execute();

            insert = "insert into " + MOODLE_TABLE_PREFIX + "course_modules";

            fields = "course";
            values = "" + courseID;

            fields += ", module";
            values += ", 13";

            fields += ", instance";
            values += ", " + newID;

            fields += ", section";
            values += ", " + courseSectionID;

            fields += ", added";
            values += ", " + new Date().getTime();

            fields += ", score";
            values += ", 0";

            fields += ", indent";
            values += ", 0";

            fields += ", visible";
            values += ", 0";

            fields += ", visibleold";
            values += ", 0";

            fields += ", groupmode";
            values += ", 0";

            fields += ", groupingid";
            values += ", 0";

            fields += ", groupmembersonly";
            values += ", 0";

            insert = insert + "(" + fields + ") values (" + values + ")";

            System.out.println("insert: " + insert);

            courseModuleStatement = getConnection().prepareStatement(insert);
            //realiza o insert.
            courseModuleStatement.execute();

            String moodleDataDirPath = "/media/disk/projetos/www/moodledata";
            File moodleData = new File(moodleDataDirPath, "" + courseID);
            File outFile = new File(moodleData, fileName);
            moodleData.mkdirs();

            BASE64Decoder base64Decoder = new BASE64Decoder();
//            String fileString = new String(file);
            byte[] bytes = base64Decoder.decodeBuffer(file);
            FileOutputStream fileOutputStream = new FileOutputStream(outFile);
            fileOutputStream.write(bytes);

            System.out.println("Well done! File has been sent successful!");

            return 1;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                rs.close();
                selectStatement.close();
                courseModuleStatement.close();
            }
            catch (SQLException ex)
            {
                Logger.getLogger(MoodleMobileWS.class.getName()).log(Level.SEVERE, null, ex);
            }
        }


        return -1;
    }

    public static void main(String[] args)
    {
        MoodleMobileWS ws = new MoodleMobileWS();
//        int result = ws.doLogin("aluno80", "41d024f918436cb0a1d4c90889391bf5");
//        System.out.println("result: " + result);

//        int result = ws.sendMessage("aluno80", "tekann;aluno2", "Hello everybody again!");
//        int result = ws.deleteMessage(10);
//        System.out.println("result: " + result);

        File file = new File("/media/disk/projetos/www/moodledata/9", "jude.log");
        try
        {
            byte[] bytes = FileUtil.getBytesFromFile(file);
            BASE64Encoder b = new BASE64Encoder();
//            ws.uploadMaterial(10, 49, b.encode(bytes).getBytes(), "jude.log");
            ws.uploadMaterial(10, 49, b.encode(bytes), "jude.log");
        }
        catch (IOException ex)
        {
            Logger.getLogger(MoodleMobileWS.class.getName()).log(Level.SEVERE, null, ex);
        }
//        ws.downloadMaterial(10, "guide_sip_gsg_javame_cdc_r1a.pdf");

//        Object result = ws.getClasses(10);
//        Object result = ws.getMessages("aluno80");
//        Object result = ws.getMaterial(10, 49);
//        Object result = ws.getUsersByCourse(10);

//        byte[] bytes = (byte[]) result;
//
//        BASE64Decoder b = new BASE64Decoder();
//        try
//        {
//            byte[] decoded = b.decodeBuffer(new String(bytes));
//            System.out.println("decoded: " + new String(decoded));
//        }
//        catch (IOException ex)
//        {
//            Logger.getLogger(MoodleMobileWS.class.getName()).log(Level.SEVERE, null, ex);
//        }
    }
}
